package com.laikan.reader.bookfriend.mactivity;

import android.content.Intent;
import android.graphics.Color;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;

import com.google.gson.Gson;
import com.laikan.library.httpvolley.helper.VolleyErrorHandler;
import com.laikan.library.httpvolley.response.HttpResponse;
import com.laikan.library.managers.ToastMgr;
import com.laikan.reader.R;
import com.laikan.reader.bookfriend.adapter.impl.AutherFragmentAdapter;
import com.laikan.reader.bookfriend.base.IView;
import com.laikan.reader.bookfriend.entity.AttentionBean;
import com.laikan.reader.bookfriend.entity.PageAutherBean;
import com.laikan.reader.bookfriend.fragment.AutherFactory;
import com.laikan.reader.bookfriend.holder.HeaderHolder;
import com.laikan.reader.bookfriend.requester.AutherRequester;
import com.laikan.reader.bookfriend.requester.SimpleRequestListener;
import com.laikan.reader.bookfriend.utils.Constant;
import com.laikan.reader.bookfriend.view.SimpleViewPagerIndicator;
import com.laikan.reader.bookfriend.view.StickyNavLayout;
import com.socks.library.KLog;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by lingyt on 2016/11/16.
 * 个人主页
 */
public class AutherActivity extends BaseTitleActivity implements IView{

    private SimpleViewPagerIndicator mIndicator;
    private ViewPager mViewPager;
    private StickyNavLayout mStickyLayout;
    private RelativeLayout mTopView;
    private HeaderHolder mHeaderHolder;
    private AutherFragmentAdapter mAdapter;
    private List mFragments = new ArrayList();
    private Gson mGson;

    @Override
    protected void onRestart() {
        super.onRestart();
        setTitleBar(getTitleBarStatus());
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_person;
    }

    /**个人主页的标题栏默认为透明的*/
    @Override
    protected boolean isTitleBarAlpha() {
        return true;
    }

    @Override
    protected void assignViews() {
        super.assignViews();
        mIndicator = (SimpleViewPagerIndicator)findViewById(R.id.id_stickynavlayout_indicator);
        mViewPager = (ViewPager)findViewById(R.id.id_stickynavlayout_viewpager);
        mStickyLayout = (StickyNavLayout)findViewById(R.id.stickyNavLayout);//添加监听，以便修改标题栏的透明度
        mTopView = (RelativeLayout) findViewById(R.id.id_stickynavlayout_topview);

        mHeaderHolder = new HeaderHolder(this);
        mTopView.addView(mHeaderHolder.getRootView());

        if (mAdapter == null){
            mAdapter = new AutherFragmentAdapter(getSupportFragmentManager(),mViewPager,mIndicator);
        }else{
            mAdapter.notifyDataSetChanged();
        }

        mGson = new Gson();
    }



    @Override
    protected void initData() {

        Intent intent = getIntent();
        String userId = intent.getStringExtra(Constant.USER_ID);

        //test  userId = "7418238";
        setAuthorId(userId);

        mFragments.add(AutherFactory.createFragment(AutherFactory.TYPE_SHORTE,"看点",getAuthorId()));
        mFragments.add(AutherFactory.createFragment(AutherFactory.TYPE_BOOK,"作品",getAuthorId()));
        mAdapter.setFragments(mFragments);
    }


    @Override
    protected void setListener() {
        mStickyLayout.setOnScrollListener(new StickyNavLayout.OnScrollListener() {
            @Override
            public void onScroll(double percent) {
                if (percent == 1){
                    setTitleBar(false);
                }else if (percent == 0){
                    setTitleBar(true);
                }
            }
        });

        mBtRight.setOnClickListener(this);//标题栏右边按钮
        mHeaderHolder.mBtFocus.setOnClickListener(this);
        sendRequestData();
    }

    private void sendRequestData() {
        loadData(1);//从第一页开始加载数据
    }

    protected void loadData(int pageNo) {
        KLog.w("load Data:开始加载第  "+pageNo+" 页数据");
        String authorId = getAuthorId();
        int bookPageNo = 1;
        AutherRequester.requestAutherHomeData(authorId,bookPageNo,pageNo,mCallback);
    }

    /*private SimpleCallback<PageAutherBean> mCallback = new SimpleCallback<PageAutherBean>(this) {

        @Override
        public void onSuccess(HttpResponse httpResponse, PageAutherBean pageAutherBean) {
            onRequestSuccess(pageAutherBean);
        }

        @Override
        public void onError(VolleyErrorHandler errorHandler) {
            onRequestError();
        }

    };*/


    private SimpleRequestListener mCallback = new SimpleRequestListener(this){

        @Override
        public void onSuccess(HttpResponse httpResponse) {
            PageAutherBean pageAutherBean = mGson.fromJson(httpResponse.responseContent,PageAutherBean.class);
            onRequestSuccess(pageAutherBean);
        }

        @Override
        public void onError(VolleyErrorHandler errorHandler) {
                onRequestError();
        }
    };

    private void onRequestError() {
        ToastMgr.showShortToast("网络异常，请检查网络设置");
    }

    private void onRequestSuccess(PageAutherBean pageAutherBean) {
        KLog.w("pageAutherBean:"+pageAutherBean);
        showData(pageAutherBean);
    }

    private void showData(PageAutherBean pageAutherBean) {

        mHeaderHolder.setData(pageAutherBean);
        mAdapter.setBeanData(pageAutherBean);
        refreshTitleBar(pageAutherBean);
    }

    private void refreshTitleBar(PageAutherBean bean) {

        if (bean.data.isMyself){
            mBtRight.setVisibility(View.INVISIBLE);
        }else{
//            mBtRight.setVisibility(View.VISIBLE);//默认都不显示
        }
        refreshTitleBar(bean.data.isAttention);
    }

    private void refreshTitleBar(boolean isAttention){
        if (isAttention){
            mBtRight.setText("已关注");
            mBtRight.setTextColor(Color.GRAY);
            mBtRight.setBackgroundResource(R.drawable.focus_shape_gray);
        }else{
            mBtRight.setText("关注");
            mBtRight.setBackgroundResource(R.drawable.focus_shape_blue);
            mBtRight.setTextColor(getResources().getColor(android.R.color.holo_blue_bright));
        }
    }

    @Override
    protected void onClickEvent(View view) {
        super.onClickEvent(view);
        switch (view.getId()){
            case R.id.title_bt_right:
            case R.id.bt_focus:
                onFocusButtonClicked(view);
                break;
        }
    }
    public static final int FLAG_ADD_ATTENTION = 1;
    public static final int FLAG_DEL_ATTENTION = 2;
    public static int currFlag = 0;

    private void onFocusButtonClicked(View view){
        Button bt = (Button) view;
        if(bt.getVisibility() == View.VISIBLE){
            if (bt.getText().equals("已关注")){
                KLog.w("开始取消关注");
                sendDelAttentionRequest();
            }else if(bt.getText().equals("关注")){
                sendAddAttentionRequest();
            }
        }
    }

    private void sendAddAttentionRequest() {
        currFlag = FLAG_ADD_ATTENTION;
        String objectId = getAuthorId();
        AutherRequester.requestAddAttention(objectId,mHandler);
    }

    private void sendDelAttentionRequest() {
        currFlag = FLAG_DEL_ATTENTION;
        String objectId = getAuthorId();
        AutherRequester.requestDelAttention(objectId,mHandler);
    }

    /*public SimpleCallback<AttentionBean> mHandler = new SimpleCallback<AttentionBean>(this) {
        @Override
        public void onSuccess(HttpResponse httpResponse, AttentionBean bean) {
            if (currFlag == FLAG_ADD_ATTENTION){
                onAddAttentionSuccess(bean);
            }else if (currFlag == FLAG_DEL_ATTENTION){
                onDelAttentionSuccess(bean);
            }
        }

        @Override
        public void onError(VolleyErrorHandler errorHandler) {
            if (currFlag == FLAG_ADD_ATTENTION){
                onAddAttentionError();
            }else if (currFlag == FLAG_DEL_ATTENTION){
                onDelAttentionError();
            }
        }
    };*/

    public SimpleRequestListener mHandler = new SimpleRequestListener(this) {
        @Override
        public void onSuccess(HttpResponse httpResponse) {
            AttentionBean bean = mGson.fromJson(httpResponse.responseContent,AttentionBean.class);
            if (currFlag == FLAG_ADD_ATTENTION){
                onAddAttentionSuccess(bean);
            }else if (currFlag == FLAG_DEL_ATTENTION){
                onDelAttentionSuccess(bean);
            }
        }

        @Override
        public void onError(VolleyErrorHandler errorHandler) {
            if (currFlag == FLAG_ADD_ATTENTION){
                onAddAttentionError();
            }else if (currFlag == FLAG_DEL_ATTENTION){
                onDelAttentionError();
            }
        }
    };

    private void onDelAttentionError() {
        ToastMgr.showShortToast("取消失败");
    }

    private void onDelAttentionSuccess(AttentionBean bean) {
        if (bean!=null && bean.result.equals("1")){
            ToastMgr.showShortToast("取消成功");
            refreshTitleBar(false);
            mHeaderHolder.setAttentionButtonStatus(false);
        }else{
            onAddAttentionError();
        }
    }

    private void onAddAttentionError() {
        ToastMgr.showShortToast("关注失败");
    }

    private void onAddAttentionSuccess(AttentionBean bean) {
        if (bean!=null && bean.result.equals("1")){
            ToastMgr.showShortToast("关注成功");
            refreshTitleBar(true);
            mHeaderHolder.setAttentionButtonStatus(true);
        }else{
            onAddAttentionError();
        }
    }


    private String mAuthorId = "";
    public void setAuthorId(String userId) {
        this.mAuthorId = userId;
    }

    public String getAuthorId() {
        return mAuthorId;
    }

    @Override
    public void showProgress() {
        showDialog();
    }

    @Override
    public void hideProgress() {
        dismissDialog();
    }
}
